<template>
    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field
                v-model="password"
                name="密码"
                label="密码"
                placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]"
            />
        </van-cell-group>
        <van-cell-group inset>
            <van-field
                v-model="repassword"
                name="密码"
                label="重复密码"
                placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]"
            />
        </van-cell-group>
        <div style="margin: 16px">
            <van-button
                :disabled="btnFlage" 
                round 
                block 
                type="primary" 
                native-type="submit"
            >
                注册
            </van-button>
        </div>
    </van-form>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import type { Ref } from 'vue'
import { dofinishregister } from "@/api/register";
import { showSuccessToast, showFailToast } from 'vant';
import { useRouter } from "vue-router";

// 创建一个 选项式 API 中的 this.$router
const router = useRouter()

// 存储用户输入的密码
const password: Ref<string> = ref('')

// 存储用户再次输入的密码
const repassword: Ref<string> = ref('')

//点击注册按钮
async function onSubmit() {
    // console.log('注册成功');
    const { data } = await dofinishregister({
        tel: window.localStorage.getItem('phoneNum') + '',
        password: password.value
    }) 
    if (data.code !== '200') {
        // 提示用户注册失败
        return showFailToast(data.message);
    }

    // 提醒用户注册成功
    showSuccessToast(data.message);

    // //临时存储
    // window.localStorage.setItem('password', password.value)

    //跳转第三个页面
    router.push('/login')

}

//根据输入框内容，控制按钮能否使用
const btnFlage = computed(() => {
    // if (password.value !== '' && password.value === repassword.value) {
    //     //满足条件，允许使用按钮
    //     return false
    // } else {
    //     //不满足条件，禁用按钮
    //     return true
    // }
    return !(password.value !== '' && password.value === repassword.value)
})

// // 侦听验证码, 控制 提交验证码 按钮能否使用
// const btnFlage: Ref<boolean> = ref(true)
// watch(
//     [ password, repassword ],
//     () => {

//         if (password.value === '' || repassword.value === '') {
//             btnFlage.value = true
//         } else {
//             btnFlage.value = false
//         }

//         if (password.value !== repassword.value) {
//             btnFlage.value = true
//         } else {
//             btnFlage.value = false
//         }
        
//     },
//     {
//         immediate: true
//     }
// )
</script>